using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Carousel;
using B.S.NewMedical.Api.Read.DTOS.Carousel;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.ContentManagement.Carousel
{
    /// <summary>
    /// 获取轮播图列表处理器
    /// </summary>
    public class GetCarouselsHandler : IRequestHandler<GetCarouselsCommand, ApiPageing<List<CarouselDto>>>
    {
        private readonly IBaseRepository<CarouselModel> _carouselRepository;
        private readonly ILogger<GetCarouselsHandler> _logger;
        private readonly IMapper _mapper;

        public GetCarouselsHandler(
            IBaseRepository<CarouselModel> carouselRepository,
            ILogger<GetCarouselsHandler> logger,
            IMapper mapper)
        {
            _carouselRepository = carouselRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiPageing<List<CarouselDto>>> Handle(GetCarouselsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取轮播图列表，查询条件：{@QueryDto}", request.QueryDto);

                var query = _carouselRepository.GetAll().Where(c => !c.IsDeleted);

                // 应用查询条件
                if (!string.IsNullOrWhiteSpace(request.QueryDto.Title))
                {
                    query = query.Where(c => c.Title != null && c.Title.Contains(request.QueryDto.Title));
                }

                if (request.QueryDto.Status.HasValue)
                {
                    query = query.Where(c => c.Status == request.QueryDto.Status);
                }

                if (request.QueryDto.CreateTimeStart.HasValue)
                {
                    query = query.Where(c => c.CreateTime >= request.QueryDto.CreateTimeStart);
                }

                if (request.QueryDto.CreateTimeEnd.HasValue)
                {
                    query = query.Where(c => c.CreateTime <= request.QueryDto.CreateTimeEnd);
                }

                // 排序：按排序号升序，然后按创建时间降序
                query = query.OrderBy(c => c.Number).ThenByDescending(c => c.CreateTime);

                // 计算总数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页
                var items = await query
                    .Skip((request.QueryDto.PageIndex - 1) * request.QueryDto.PageSize)
                    .Take(request.QueryDto.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射到DTO
                var carouselDtos = _mapper.Map<List<CarouselDto>>(items);

                _logger.LogInformation("成功获取轮播图列表，总数：{TotalCount}", totalCount);

                return new ApiPageing<List<CarouselDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取轮播图列表成功",
                    Data = carouselDtos,
                    TotaCount = totalCount,
                    TotaPage = (int)Math.Ceiling((double)totalCount / request.QueryDto.PageSize)
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取轮播图列表时发生异常");
                return new ApiPageing<List<CarouselDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取轮播图列表失败：" + ex.Message,
                    Data = new List<CarouselDto>()
                };
            }
        }
    }
}